<template>
  <xr-create
    :loading="loading"
    :title="title"
    :confirm-button-text="sureBtnTitle"
    :show-confirm="config.showConfirm"
    :show-cancel="config.showCancel"
    @close="close"
    @save="saveClick">
    <i
      slot="title-append"
      class="wk wk-icon-fill-help wk-help-tips"
      data-type="12"
      data-id="39" />
    <create-sections
      :title="$t('crm.receivables.7ac2523a1f5346b76c65b9b6d61a2648')">
      <el-form
        ref="crmForm"
        :model="fieldForm"
        :rules="fieldRules"
        :validate-on-rule-change="false"
        class="wk-form"
        label-position="top">
        <wk-form-items
          v-for="(children, index) in fieldList"
          :key="index"
          :field-from="fieldForm"
          :field-list="children"
          @change="formChange">
          <template slot-scope="{ data }">
            <crm-relative-cell
              v-if="data && data.formType == 'customer'"
              :value="fieldForm[data.field]"
              :disabled="data.disabled"
              data-type="customer"
              @value-change="otherChange($event, data)"
            />
            <crm-relative-cell
              v-if="data && data.formType == 'contract'"
              :value="fieldForm[data.field]"
              :disabled="data.disabled"
              :props="data.props"
              :data-type="data.formType"
              @value-change="otherChange($event, data)"
            />
            <xh-receivables-plan
              v-if="data && data.formType == 'receivables_plan'"
              :value="fieldForm[data.field]"
              :disabled="data.disabled"
              :receivables-id="editId"
              :relation="data.relation"
              @value-change="otherChange($event, data)" />
          </template>
        </wk-form-items>
      </el-form>
    </create-sections>

    <!-- <create-sections
      v-if="wkFlowList"
      :title="$t('crm.receivables.42a1c5e4cd145f668ad174dddebb3783')">
      <template slot="header">
        <el-tooltip
          v-if="flowRemarks"
          :content="flowRemarks"
          effect="dark"
          placement="top">
          <i class="wk wk-help wk-help-tips" style="margin-left: 8px;" />
        </el-tooltip>
      </template>
      <wk-approval-flow-apply
        :data="wkFlowList"
        :approver-edit-auth="approverEditAuth"
        :is-edit="examineInfo.hasOwnProperty('examineStatus') && examineInfo.examineStatus == 2"
        :carbon-copy-edit-auth="carbonCopyEditAuth"
        :examine-advanced-setting="examineAdvancedSetting"
        style="padding: 15px;"
      />
    </create-sections> -->

    <create-sections
      v-if="wkFlowList"
      title="审核信息">
      <template slot="header">
        <el-tooltip
          v-if="flowRemarks"
          :content="flowRemarks"
          effect="dark"
          placement="top">
          <i class="wk wk-help wk-help-tips" style="margin-left: 8px;" />
        </el-tooltip>
      </template>
      <wk-af-new-apply
        ref="afNewApply"
        :data="wkFlowList"
        :approver-edit-auth="approverEditAuth"
        :detail="examineAdvancedSetting"
        style="padding: 15px;" />
    </create-sections>

    <el-button
      v-if="!config.getFields"
      slot="footer"
      type="primary"
      plain
      @click.native="debouncedSaveField(true)">{{ $t('crm.receivables.69dfed1e98fc044bdfd3e506c9ad59b2') }}</el-button>

    <template slot="footer-left">
      <slot name="footer" />
    </template>
  </xr-create>
</template>

<script>
import { filedGetFieldAPI } from '@/api/crm/common'
import { crmReceivablesSaveAPI } from '@/api/crm/receivables'

import XrCreate from '@/components/XrCreate'
import CreateSections from '@/components/CreateSections'
import WkFormItems from '@/components/NewCom/WkForm/WkFormItems'
// import WkApprovalFlowApply from '@/components/Examine/WkApprovalFlowApply'
import WkApprovalFlowApplyMixin from '@/components/Examine/mixins/WkApprovalFlowApply'
import WkAfNewApply from '@/components/Examine/WkAfNewApply'

import crmTypeModel from '@/views/crm/model/crmTypeModel'
import tagProps from '@/views/crm/model/tagDefaultProps'
import CustomFieldsMixin from '@/mixins/CustomFields'
import { debounce } from 'throttle-debounce'
import CrmCreateMixin from '@/mixins/CrmCreateMixin'
import { objDeepCopy } from '@/utils'
import { isEmpty } from '@/utils/types'

export default {
  // 新建编辑
  name: 'ReceivablesCreate',

  components: {
    XrCreate,
    CreateSections,
    CrmRelativeCell: () => import('@/components/CreateCom/CrmRelativeCell'),
    XhReceivablesPlan: () => import('../receivablesPlan/components/XhReceivablesPlan'),
    // WkApprovalFlowApply,
    WkFormItems,
    WkAfNewApply
  },

  mixins: [CustomFieldsMixin, WkApprovalFlowApplyMixin, CrmCreateMixin],

  props: {
    action: {
      type: Object,
      default: () => {
        return {
          type: 'save',
          id: '',
          data: {}
        }
      }
    },
    examineInfo: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },

  data() {
    return {
      loading: false,
      baseFields: [],
      fieldList: [],
      fieldForm: {},
      fieldRules: {},

      // 审批信息
      flowRemarks: '',
      wkFlowList: null, // 有值有审批流
      approverEditAuth: false, // 固定审批人是否可修改
      carbonCopyEditAuth: false // 固定抄送人是否可修改
    }
  },

  computed: {
    title() {
      if (this.config.title) return this.config.title

      return this.action.type === 'update' ? this.$t('crm.receivables.4b04f4e08fa7490f659b0140c31c521a') : this.$t('crm.receivables.5c02f775b2887b024da1fad8716e4cda')
    },

    editId() {
      return this.action.type == 'update' ? this.action.id : ''
    },

    // 确认名称
    sureBtnTitle() {
      if (this.wkFlowList) {
        return this.$t('crm.receivables.a1bee80cc47ee3492a122b83a3982f89')
      }
      return this.$t('crm.receivables.7b09d396abd7ab4fcd7bf4c4545ff605')
    }
  },

  watch: {},

  created() {
    this.debouncedSaveField = debounce(300, this.saveClick)

    if (this.config.getFields) {
      this.getCustomField()
    } else {
      this.getField()
    }
  },

  mounted() {},

  beforeDestroy() {},

  methods: {
    /**
     * 获取数据
     */
    getField() {
      this.loading = true
      const params = {
        label: crmTypeModel.receivables
      }

      if (this.action.type == 'update') {
        params.id = this.action.id
      }

      filedGetFieldAPI(params)
        .then(res => {
          const list = res.data || []

          const baseFields = []
          const fieldList = []
          const fieldForm = {}

          list.forEach(children => {
            const fields = []
            children.forEach(item => {
              const temp = this.getFormItemDefaultProperty(item)
              temp.show = true

              const canEdit = this.getItemIsCanEdit(item, this.action.type)
              // 是否可编辑
              temp.disabled = !canEdit

              // 禁止某些业务组件选择
              if (temp.formType == 'receivables_plan' ||
                temp.formType == 'contract' ||
                temp.formType == 'customer') {
                if (this.action.type == 'relative') {
                  const relativeDisInfos = {
                    contacts: { customer: true },
                    customer: { customer: true },
                    business: { customer: true },
                    contract: { customer: true, contract: true },
                    receivablesPlan: { customer: true, contract: true, receivables_plan: true }
                  }

                  // 在哪个类型下添加
                  const relativeTypeDisInfos = relativeDisInfos[this.action.crmType]
                  if (relativeTypeDisInfos) {
                  // 包含的字段值
                    temp.disabled = relativeTypeDisInfos[item.formType] || false
                  }
                } else if (this.action.type != 'update') {
                  temp.disabled = item.formType === 'contract' || item.formType === 'receivables_plan'
                }
              }

              if (temp.formType == 'field_tag') {
                temp['tagProps'] = tagProps({ params: { type: crmTypeModel.receivables }})
              }

              // 处理关联
              // 回款计划 需要合同信息
              if (item.formType === 'receivables_plan') {
                const contractItem = this.getItemRelatveInfo(list, 'contract')
                if (contractItem) {
                  contractItem['moduleType'] = 'contract'
                  const customerItem = this.getItemRelatveInfo(list, 'customer')
                  if (customerItem) {
                    temp['relation'] = {
                      ...contractItem,
                      ...customerItem
                    }
                  } else {
                    temp['relation'] = contractItem
                  }
                } else {
                  temp['relation'] = {}
                }
                // 合同 需要客户信息
              } else if (item.formType == 'contract') {
                const customerObj = this.getItemRelatveInfo(list, 'customer')
                if (customerObj) {
                  temp.props = {
                    params: {
                      searchList: [
                        { formType: 'text', name: 'customer_id', type: 1, values: [customerObj.customerId] },
                        { formType: 'checkStatus', name: 'checkStatus', type: 1, values: [1, 10] }
                      ]
                    }
                  }
                } else {
                  temp.props = null
                }
              }

              // 特殊字段允许多选
              this.getItemRadio(item, temp)

              // 获取默认值
              if (temp.show) {
                fieldForm[temp.field] = this.getItemValue(item, this.action.data, this.action.type)
                if (this.action.type == 'relative' && ['receivablesPlanId', 'returnTime', 'money', 'returnType', 'remark'].includes(temp.field)) {
                  fieldForm[temp.field] = this.action.data[temp.field]
                }
              }
              fields.push(temp)
              baseFields.push(item)
            })
            fieldList.push(fields)
          })

          this.baseFields = baseFields
          this.fieldList = fieldList

          const result = this.getFormContentByOptionsChange(fieldList, fieldForm)
          this.fieldForm = result.fieldForm
          this.fieldRules = result.fieldRules

          // 审核信息
          const examineParams = {
            label: 2
          }
          if (this.examineInfo.hasOwnProperty('examineStatus') && this.examineInfo.examineStatus == 2) {
            const { recordId } = this.examineInfo
            examineParams.recordId = recordId
          }

          this.initWkFlowData({
            params: examineParams,
            fieldForm: this.fieldForm
          }, res => {
            const list = res.list
            list.forEach(item => {
              if (item.rangeType === 2 || item.rangeType == 3) {
                item.finalUserList = objDeepCopy(item.userList)
                item.userList = []
              }
            })

            this.wkFlowList = res.list
            this.flowRemarks = res.resData ? res.resData.remarks : ''

            // 固定审批人/抄送人修改权限
            const modifyPermissionType = this.examineAdvancedSetting?.modifyPermissionType
            if (isEmpty(modifyPermissionType)) {
              this.approverEditAuth = true
              this.carbonCopyEditAuth = true
            } else {
              this.approverEditAuth = !modifyPermissionType.includes(1)
              this.carbonCopyEditAuth = !modifyPermissionType.includes(2)
            }
          })

          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
     * @description: 自定义获取
     * @return {*}
     */
    getCustomField() {
      this.loading = true
      this.config.getFields().then(fields => {
        console.log('fields---', fields)

        const list = this.convertToTwoFields(fields)
        const baseFields = []
        const fieldList = []
        const fieldForm = {}

        list.forEach(children => {
          const fields = []
          children.forEach(item => {
            const temp = this.getFormItemDefaultProperty(item)
            temp.show = true

            if (item.formType === 'serial_number') {
              temp.disabled = !(item.authLevel == 3) // 3是可编辑
              const setItem = temp.setting.find(obj => obj.type === 1)
              if (setItem) {
                // 优先读取字段里是否允许输入配置
                const allowedInput = setItem.allowedInput == 1
                if (allowedInput && temp.disabled) { // 如果禁止改为0
                  setItem.allowedInput = 0
                }
              }
            } else {
              const canEdit = this.getItemIsCanEdit(item, this.action.type)
              // 是否可编辑
              temp.disabled = !canEdit
            }

            // 禁止某些业务组件选择
            // if (temp.formType == 'receivables_plan' ||
            //   temp.formType == 'contract' ||
            //   temp.formType == 'customer') {
            //   if (this.action.type == 'relative') {
            //     const relativeDisInfos = {
            //       contacts: { customer: true },
            //       customer: { customer: true },
            //       business: { customer: true },
            //       contract: { customer: true, contract: true },
            //       receivablesPlan: { customer: true, contract: true, receivables_plan: true }
            //     }

            //     // 在哪个类型下添加
            //     const relativeTypeDisInfos = relativeDisInfos[this.action.crmType]
            //     if (relativeTypeDisInfos) {
            //     // 包含的字段值
            //       temp.disabled = relativeTypeDisInfos[item.formType] || false
            //     }
            //   } else if (this.action.type != 'update') {
            //     temp.disabled = item.formType === 'contract' || item.formType === 'receivables_plan'
            //   }
            // }

            if (temp.formType == 'field_tag') {
              temp['tagProps'] = tagProps({ params: { type: crmTypeModel.receivables }})
            }

            // 处理关联
            // 回款计划 需要合同信息
            if (item.formType === 'receivables_plan') {
              const contractItem = this.getItemRelatveInfo(list, 'contract')
              if (contractItem) {
                contractItem['moduleType'] = 'contract'
                temp['relation'] = contractItem
              } else {
                temp['relation'] = {}
              }
              // 合同 需要客户信息
            } else if (item.formType == 'contract') {
              const customerObj = this.getItemRelatveInfo(list, 'customer')
              if (customerObj) {
                temp.props = {
                  params: {
                    searchList: [
                      { formType: 'text', name: 'customer_id', type: 1, values: [customerObj.customerId] },
                      { formType: 'checkStatus', name: 'checkStatus', type: 1, values: [1, 10] }
                    ]
                  }
                }
              } else {
                temp.props = null
              }
            }

            // 特殊字段允许多选
            this.getItemRadio(item, temp)

            // 获取默认值
            if (temp.show) {
              fieldForm[temp.field] = this.getItemValue(item, this.action.data, this.action.type)
              // if (this.action.type == 'relative' && ['receivablesPlanId', 'returnTime', 'money', 'returnType', 'remark'].includes(temp.field)) {
              //   fieldForm[temp.field] = this.action.data[temp.field]
              // }
            }
            fields.push(temp)
            baseFields.push(item)
          })
          fieldList.push(fields)
        })

        this.baseFields = baseFields
        this.fieldList = fieldList

        const result = this.getFormContentByOptionsChange(fieldList, fieldForm)
        this.fieldForm = result.fieldForm
        this.fieldRules = result.fieldRules

        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    /**
     * 保存
     */
    saveClick(isDraft = false) {
      this.loading = true
      const crmForm = this.$refs.crmForm
      crmForm.validate(valid => {
        if (valid) {
          // 如果 afNewApply 说明没有开始审批流
          const wkFlowResult = this.$refs.afNewApply ? this.$refs.afNewApply.getParams() : {
            pass: true,
            flowParams: { list: [] }
          }
          if (wkFlowResult.pass || isDraft) {
            const params = this.getSubmiteParams([].concat.apply([], this.fieldList), this.fieldForm)
            if (isDraft) {
              params.entity.checkStatus = 5
            }
            // 审批流
            const dataMap = this.getWkFlowDataMap(this.fieldForm, wkFlowResult.flowParams.paramsData?.userFieldNames)
            params.examineFlowData = {
              label: this.examineAdvancedSetting.label,
              dataMap,
              flowDataList: wkFlowResult.flowParams.list
            }
            this.submiteParams(params)
          } else {
            this.loading = false
            this.$message.error(this.$t('crm.receivables.9796f77ef0fdbf33bb7e417aee678534'))
          }
        } else {
          this.loading = false
          // 提示第一个error
          this.getFormErrorMessage(crmForm)
          return false
        }
      })
    },

    /**
     * 提交上传
     */
    submiteParams(params) {
      if (this.action.type == 'update') {
        params.entity.receivablesId = this.action.id
        params.entity.batchId = this.action.batchId
      }

      // 相关添加时候的多余提交信息
      if (
        this.action.relativeData &&
        Object.keys(this.action.relativeData).length
      ) {
        params = { ...params, ...this.action.relativeData }
      }

      crmReceivablesSaveAPI(params)
        .then(res => {
          this.loading = false

          this.$message.success(
            this.action.type == 'update' ? this.$t('crm.receivables.12d4cc548c920f057ceb81617fa72582') : this.$t('crm.receivables.590ed5a26d2d8bb25d2b184a5f2562fe')
          )

          this.close()

          // 保存成功
          this.$emit('save-success', {
            type: 'receivables'
          })
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
     * 验证唯一
     */
    UniquePromise({ field, value }) {
      return this.getUniquePromise(field, value, this.action)
    },

    /**
     * change
     */
    formChange(field, index, value, valueList) {
      // 审批流逻辑
      // this.debouncedGetWkFlowList(field.field, this.fieldForm)

      if ([
        'select',
        'checkbox'
      ].includes(field.formType) &&
          field.remark === 'options_type' &&
          field.optionsData) {
        const { fieldForm, fieldRules } = this.getFormContentByOptionsChange(this.fieldList, this.fieldForm)
        this.fieldForm = fieldForm
        this.fieldRules = fieldRules
      }
    },

    /**
     * 地址change
     */
    otherChange(data, field) {
      if (field.formType === 'customer') {
        this.itemsForEach(this.fieldList, fieldItem => {
          if (fieldItem.formType === 'contract') {
            // 如果是合同 改变合同样式和传入客户ID
            if (data.value.length > 0) {
              fieldItem.disabled = false
              const customerItem = data.value[0]
              fieldItem.props = {
                params: {
                  searchList: [
                    { formType: 'text', name: 'customer_id', type: 1, values: [customerItem.customerId] },
                    { formType: 'checkStatus', name: 'checkStatus', type: 1, values: [1, 10] }
                  ]
                }
              }
            } else {
              fieldItem.disabled = true
              fieldItem.props = null
            }
            this.fieldForm[fieldItem.field] = []
          } else if (fieldItem.formType === 'receivables_plan') {
            fieldItem.disabled = true
            fieldItem.props = null
            this.fieldForm[fieldItem.field] = ''
          }
        })
      } else if (field.formType === 'contract') {
        const planItem = this.getItemWithFromType(this.fieldList, 'receivables_plan')
        if (planItem) {
          if (data.value.length > 0) {
            planItem.disabled = false
            var contractItem = data.value[0]
            contractItem['moduleType'] = 'contract'
            planItem['relation'] = contractItem
          } else {
            planItem.disabled = true
            planItem['relation'] = {}
          }
          this.fieldForm[planItem.field] = ''
        }
      } else if (field.formType === 'receivables_plan') {
        const dataValue = data.data || {}
        this.fieldForm.returnTime = dataValue.returnDate
        this.fieldForm.money = dataValue.money
        this.fieldForm.returnType = dataValue.returnType
      }
      this.$set(this.fieldForm, field.field, data.value)
      this.$refs.crmForm.validateField(field.field)
    },

    /**
     * 关闭
     */
    close() {
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped>
.wk-form {
  ::v-deep .el-form-item.is-product {
    flex: 0 0 100%;
    width: 0;
  }
}
</style>
